package com.jm.product.controller;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.java.framework.common.pagination.OrderBy;
import com.java.framework.common.pagination.SearchBean;
import com.jm.product.controller.core.BaseController;
import com.jm.product.entity.GoodsCat;
import com.jm.product.entity.GoodsType;
import com.jm.product.service.GoodsTypeService;
import com.jm.product.utils.UploadFileUtils;

/**
 * 商品分类Controller
 * @author sunshine
 * @version 2017-07-04
 */
@Controller
@RequestMapping(value = "product/goodsCat")
public class GoodsCatController extends BaseController<GoodsCat,Integer> {

	private static final String SUB_UPLOAD_FOLDER = "cat";
	@Resource
	private GoodsTypeService typeService;
	
	protected String listPage() {

		return "product/goodsCatList";
	}

	public String form(GoodsCat goodsCat, Model model) {
		/*
		if (null != goodsCat && null != goodsCat.getId()){
			this.data = service.getById(goodsCat.getId());
			model.addAttribute("goodsCat", this.data);
		}
		*/
		model.addAttribute("goodsCat", this.data);
		
		//类型
		List<GoodsType> types = typeService.list(null, null, 0, Integer.MAX_VALUE) ;
		model.addAttribute("types", types);
		
		return "product/goodsCatForm";
	}
	
	@Override
	public String save(GoodsCat data, Model model, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		if (request instanceof MultipartHttpServletRequest) {
			// 对文件进处理
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
            String uploadRootPath = session.getServletContext().getRealPath("/") ;
            String uploadFolder = this.uploadPath + "/" + SUB_UPLOAD_FOLDER ;
            // 获取上传的文件
            Map<String, MultipartFile> fileMap = multipartHttpServletRequest.getFileMap();
            for(Map.Entry<String, MultipartFile> entry : fileMap.entrySet()){
                try {
                	//TODO:这里可改为云存储，目前暂存储在项目目录下
                	String filePath = UploadFileUtils.upload(entry.getValue(), uploadRootPath, uploadFolder);
					data.setImage(filePath);
				} catch (Exception e) {
					e.printStackTrace();
				}
            }
        }
		return super.save(data, model, redirectAttributes, request);
	}

	public String savePage() {

		return "redirect:/product/goodsCat/treeTable?repage";
	}


    @RequestMapping("tree")
    public String tree(){

    	return "product/goodsCatTree";
    }

    @RequestMapping("treeData")
    @ResponseBody
    public List<Map<String, Object>> treeData(@RequestParam(required=false) Integer id,
		HttpServletRequest request, HttpServletResponse response, Model model){
    	List<SearchBean> sbs = Lists.newArrayList() ;
        if(id == null){
        	sbs.add(new SearchBean("parent", null, SearchBean.Operator.EQ)) ;
        } else {
        	sbs.add(new SearchBean("parent.id", id, SearchBean.Operator.EQ)) ;
        }
        //order by
        List<OrderBy> obs = null;
		//obs = Lists.newArrayList(new OrderBy("creationTime", OrderBy.OrderByDirection.ASC));
        List<GoodsCat> list = this.service.list(sbs, obs, 0, Integer.MAX_VALUE);
        List<Map<String, Object>> rtns = Lists.newArrayList() ;
        for(GoodsCat goodsCat : list){
        	Map<String, Object> map = Maps.newHashMap() ;
        	map.put("id", goodsCat.getId());
        	map.put("name", goodsCat.getName());
        	map.put("pid", goodsCat.getParent() == null ? "0" : goodsCat.getParent().getId());
			//you can continue add any other field here
			if(goodsCat.getChildren().size() > 0) {
				map.put("isParent","true");
			} else {
				map.put("isParent","false");
			}
        	rtns.add(map);
        }
		return rtns;
	}

	@RequestMapping("treeTable")
	public String treeTable(){

		return "product/goodsCatTreeTable";
	}

	@RequestMapping("treeTableData")
	@ResponseBody
	public List<Map<String, Object>> treeTableData(@RequestParam(required=false) Integer id, HttpServletRequest request){
        List<Map<String, Object>> rtns = Lists.newArrayList() ;
        List<SearchBean> sbs = Lists.newArrayList() ;
        if(id == null){
        	sbs.add(new SearchBean("parent", null, SearchBean.Operator.EQ)) ;
        } else {
        	sbs.add(new SearchBean("parent.id", id, SearchBean.Operator.EQ)) ;
        }
        //order by
        List<OrderBy> obs = null;
        obs = Lists.newArrayList(new OrderBy("catOrder", OrderBy.OrderByDirection.ASC));
        List<GoodsCat> list = this.service.list(sbs, obs, 0, Integer.MAX_VALUE);
        for(GoodsCat goodsCat : list){
        	Map<String, Object> map = Maps.newHashMap() ;
			map.put("id", goodsCat.getId());
			//名称
			map.put("name",goodsCat.getName());
			
			//类型
			map.put("goodsType",goodsCat.getGoodsType().getName());
			//是否显示
			map.put("listShow",("1".equals(goodsCat.getListShow()) ? "是" : "否"));
			//排序
			map.put("catOrder",goodsCat.getCatOrder());

			//parent id
			map.put("pid", goodsCat.getParent() == null ? "0" : goodsCat.getParent().getId());
        	if(goodsCat.getChildren().size() > 0) {
				map.put("hasChild","true");
			}
			rtns.add(map);
        }
        return rtns ;
	}
}
